<template>
  <view class="pd16_15">
      <view class="box over-hide">
        <view class="recharge-header">
          <image :src="statics.moneyRecharge"></image>
          <view class="main pd20_15">
            <view class="ft14 cl-w9">{{$t("refill.mywallet")}}</view>
            <view class="mt8 ftw600 ft32 cl-w">{{Math.trunc(userinfo.money || 0)}}</view>
          </view>
        </view>
        <navigator url="/pages/client/vipcard/moneylog">
          <view class="pd10_15 flex alcenter space">
            <text class="ft14 ftw600 cl-main">{{$t("refill.detail")}} </text>
            <text class="iconfont iconicon_arrow_circle ft18" :style="{color:'#0CC04B'}"></text>
          </view>
        </navigator>
      </view>

      <view class="mt20">
        <text class="ft16 ftw600">{{$t('refill.title')}}</text>
        <text class="ft12 ml10" style="color: var(--gray-500, #AEADB6);">{{$t("refill.topup.tips")}}</text>
      </view>

      <view class="topup-list mt30">
        <view v-for="(item,index) in moneyList" :key="index" class="topup-list-item flex space"
          :class="{'recommend': item.isRecommend, 'hot': item.isHot}" @click="payConfirmHandle(item)">
          <view v-if="item.isRecommend" class="recommend"></view>
          <view class="money">
            <text class="ft18 ftw600 cl-default">{{item.account + (item.extra>0 ? '+' : '')}}</text>
            <text class="ft18 ftw600 cl-primary" v-if="item.extra>0">{{item.extra}}</text>
            <text class="ft14 cl-default" style="margin-left: 6rpx">{{$t('common.coin.name')}}</text>
          </view>
          <view class="block ft13 mt2 cl-primary topup-ratio">+{{item.ratio}}%</view>
          <button class="ft14 cl-w ftw600">$ {{item.price}}</button>
        </view>
      </view>

      <uni-popup ref="payTypeModal" type="bottom" style="z-index: 9999;">
        <view class="pay-type-box">
          <view class="pay-type-title">
            <text class="ft16">{{$t("refill.modal.title")}}</text>
            <image @click="handleClose" class="pay-type-close" src="@/static/icon/close.png"></image>
          </view>
          <view class="pay-type-info">
            <view class="flex center" style="color: #000; align-items: baseline;">
              <text class="ft16 ftw600" style="margin-right: 6rpx;">$</text>
              <text class="ft32 ftw600">{{selectMoney.price}}</text>
            </view>
            <view class="ft14 text-center" style="color: #00CC5A">
              {{$t("refill.modal.tips")}}&nbsp;{{selectMoney.account}}+{{selectMoney.extra}}&nbsp;{{$t("common.coin.name")}}
            </view>
          </view>
          <view class="pay-type-list">
            <!-- <scroll-view style="height: 60vh;" :scroll-y="scrollY"> -->
            <radio-group class="pay-type-list-box" @change="changeCode">
              <view v-for="item in payType" class="pay-type-item flex space alcenter"
                :class="{'disabled': selectMoney.price < item.min, 'selected': item.code == selectPayCode}"
                @click="handleRadioChecked(item)">
                <image :src="item.icon" />
                <view class="ft16 pay-type-item-title">{{item.name}}</view>
                <view v-if="selectMoney.price < item.min" class="ft14" style="padding-right: 16rpx; color: #AEADB6">
                  金額大於NT${{item.min}}可用
                </view>
                <radio :disabled="selectMoney.price < item.min" style="transform:scale(0.9)" :value="item.code"
                  :checked="selectPayCode == item.code" color="#00CC5A" />
              </view>
            </radio-group>
            <!-- </scroll-view> -->
          </view>
          <view class="pay-type-footer" :class="{'has-more': scrollY}">
            <button v-show="selectPayCode=='CARDPAY'"  @click="wooshPayHandle()" class="pay-type-btn">{{$t("refill.modal.purchase")}}</button>
            
            <view v-show="selectPayCode=='PAYPAL'" id="paypal-button-container" style="height: 100rpx;"></view>
          </view>
        </view>
      </uni-popup>
    </view>
</template>

<script>
  import {
    loadScript
  } from "@paypal/paypal-js";
  let paypal;
  export default {
    data() {
      return {
        vid: 0,
        mid: 0,
        moneyList: [],
        tdnum: '901',
        openid: '',
        numa: '',
        userinfo: '',
        payPrice: 0,
        selectMoney: {},
        selectPayCode: '',
        clientSecret: '',
        orderID: '',
        payType: [
          {
            name: 'Master/VISA Card',
            code: 'CARDPAY',
            icon: '../../../static/img/payment/CARDPAY.png',
            min: 0
          },
          {
            name: 'PayPal',
            code: 'PAYPAL',
            icon: '../../../static/img/payment/PAYPAL.png',
            min: 0
          },
        ],
        scrollY: false,
        paypalInitStatus: false,
        wooshpayStatus: false
      }
    },
    computed: {
      // payType () {
      //   const list = [{
      //       name: 'PayPal',
      //       code: 'PAYPAL',
      //       icon: '../../../static/img/payment/PAYPAL.png',
      //       min: 0
      //     }];
          
      //   if (uni.getStorageSync('testWoosh') == 1) {
      //     list.push({
      //       name: 'Master Card / VISA Card',
      //       code: 'CARDPAY',
      //       icon: '../../../static/img/payment/CARDPAY.png',
      //       min: 0
      //     })
      //   }
      //   return list
      // }
    },
    onLoad(e) {
      const that = this
      if (e.price) {
        that.num = e.price
      }
      if (e.vid) {
        that.vid = e.vid
      }
      if (e.mid) {
        that.mid = e.mid
      }
      if (e.m_order) {
        uni.request({
          url: that.configs.apiUrl + '/api/paywx/paytwdone',
          data: {
            m_order: e.m_order,
          },
          success(res) {
            if (res.data.code == 1) {
              uni.showToast({
                title: 'Recharged successfully'
              })

              that.GAHandle('purchase', res.data.data.amount, {
                currency: 'USD',
                mid: that.mid,
                vid: that.vid
              })

            } else {
              uni.showToast({
                title: 'Recharged failed',
              })
            }
          },
          fail() {
            uni.showToast({
              title: 'Recharged failed',
            })
          }
        })
      }
      if (e.paystatus) {
        if (e.paystatus == 1) {
          that.GAHandle('purchase', e.amount, {
            currency: 'USD',
            mid: that.mid,
            vid: that.vid
          })
          
          if (that.vid && that.mid) {
            uni.showModal({
              title: '',
              content: 'Recharged successfully',
              showCancel: false,
              success(e) {
                uni.redirectTo({
                  url: `/pages/client/tuan/detail?vid=${that.vid}&mid=${that.mid}`
                })
              }
            })
          } else {
            uni.showToast({
              title: 'Recharged successfully',
              duration: 2000
            })
          }
        }
        
        if (e.paystatus == 0) {
          uni.showToast({
            title: 'Recharged failed',
          })
        }
      }
      that.getTopupList();
      try {
        that.initPaypal()
      } catch (error) {
        console.error("failed to load the PayPal JS SDK script", error);
      }
    },
    onShow() {
      this.ongrzlTap();
    },
    methods: {
      async wooshPayHandle () {
        const that = this;
        const mType = that.selectPayCode || 'CARDPAY';
        const mPrice = that.selectMoney.price || 0;
        if (mType == '') {
          uni.showToast({
            title: 'Please select payment method',
            icon: "none"
          });
          return false;
        }
        
        if (!mPrice) {
          uni.showToast({
            title: 'The amount is incorrect',
            icon: "none"
          });
          return false
        }
        uni.showLoading({
          title: 'Payment order generation in progress',
          mask: true
        });
        
        let dataParams = {
          id: that.selectMoney.id, // 充值档位id
          token: uni.getStorageSync("userinfo").token,  // 用户token
          total: mPrice, // 充值金额
          m_code: mType, // 充值方式code
          tdnum: that.tdnum,  // 固定值
          url: `${that.configs.webUrl}/pages/client/vipcard/recharge`, // 跳转前端路径
          cancelUrl: location.href, // 取消支付返回路径
          vid: that.vid, // 发起支付剧集id
          mid: that.mid, // 发起支付剧集视频id
        }
          
        if (that.vid) {
          dataParams.loginpay = 1
        }
        uni.request({
        	url: that.configs.apiUrl+'/api/wooshpay/orders',
        	data: dataParams,
        	success: res =>{
            that.GAHandle('begin_checkout', mPrice, {
              code: mType,
              item_id: mType
            })
            
        		if(res.data.code==1){
              uni.showLoading({
                title: 'redirect to payment page',
                mask: true
              })
        			// console.log(res.data.data.url);
              // window.open(decodeURIComponent(res.data.data.url), '_self')
              setTimeout(()=>{
                location.href = decodeURIComponent(res.data.data.url);
              }, 1000)
        			///index/paydsf?out_trade_no=2206131027251
        		}else{
        			uni.showToast({ title: res.data.msg,icon:"none" });
        		}
        	},
        	fail: (data, code) => {
            uni.hideLoading();
            uni.showToast({ title: 'recharge failed',icon:"none" });
        	}
        });
        // that.$refs.payTypeModal.close();
      },
      myRequest(options) {
        const that = this;
        return new Promise((resolve, reject) => {
          // 封装主体：网络请求
          uni.request({
            url: that.configs.apiUrl + options.url,
            data: options.data || {},
            method: options.method || 'GET', // 默认值GET，如果有需要改动，在options中设定其他的method值
            success: (res) => {
              resolve(res)
            },
            fail: (err) => {
              // 页面中弹框显示失败
              uni.showToast({
                title: 'network error'
              })
              // 返回错误消息
              reject(err)
            }
          })
        })
      },
      async initPaypal() {
        paypal = await loadScript({
          clientId: this.configs.paypalClientId,
          components: 'buttons',
          disableFunding: 'credit,card',
          currency: 'USD',
          // debug: true
        });
        this.paypalInitStatus = true;
      },
      async initPaypalButton() {
        const that = this;
        if (paypal) {
          try {
            await paypal.Buttons({
              style: {
                layout: 'vertical',
                color: 'gold',
                shape: 'pill',
                label: 'paypal',
              },
              createOrder: that.createOrderHandle,
              onApprove: function(data, actions) {
                try {
                  return uni.request({
                    url: `${that.configs.apiUrl}/api/paypal/capture`,
                    method: "GET",
                    data: {
                      token: uni.getStorageSync("userinfo").token,
                      order_id: data.orderID
                    },
                    success(res) {
                      const orderData = res.data
                      if (orderData.code === 1) {
                        uni.showToast({
                          title: 'Recharged successfully'
                        })
                        that.$refs.payTypeModal.close();
                        that.selectMoney = {};
                        that.ongrzlTap();
                      } else {
                        return actions.restart();
                      }
                      const errorDetail = orderData?.details?.[0];
                      console.log(orderData)
                    },
                    fail(error) {
                      console.error(error);
                      const container = document.querySelector("#result-message");
                      container.innerHTML =
                        `Sorry, your transaction could not be processed...<br><br>${error}`;
                    }
                  });
                } catch (error) {
                  console.error({
                    error
                  });
                  uni.showModal({
                    title: "Prompt",
                    content: `Sorry, your transaction could not be processed...<br><br>${error}`
                  })
                }
              },
            }).render("#paypal-button-container");
          } catch (error) {
            console.error("failed to render the PayPal Buttons", error);
          }
        }
      },
      async createOrderHandle() {
        const that = this
        // try {
        let orderId = ''

        const res = await that.myRequest({
          url: '/api/paypal/orders',
          data: {
            id: that.selectMoney.id,
            token: uni.getStorageSync("userinfo").token,
            vid: that.vid,
            mid: that.mid
          }
        })
        // console.log(res)
        if (res.data.code == 1) {
          return res.data.data.id
        } else {
          uni.showToast({
            content: 'failed!'
          })
          return false;
        }
        // console.log(res)
        // } catch (error) {
        // console.log(error)
        // }
      },
      getTopupList() {
        const that = this
        uni.request({
          url: that.configs.apiUrl + '/api/paypal/list',
          data: {
            token: uni.getStorageSync("userinfo").token
          },
          success(res) {
            if (res.data.code === 1) {
              that.moneyList = res.data.data
            }
          }
        })
      },
      changeCode(e) {
        this.selectPayCode = e.detail.value;
      },
      handleRadioChecked(item) {
        if (item.min > this.selectMoney.price) return;
        this.selectPayCode = item.code;
      },
      handleClose() {
        this.$refs.payTypeModal.close();
      },
      payConfirmHandle(item) {
        const that = this;
        that.selectMoney = item;
        that.selectPayCode = 'CARDPAY';
        that.$refs.payTypeModal.open('bottom');

        setTimeout(() => {
          that.initPaypalButton()
        }, 500)

        that.GAHandle('c_recharge_level', item.price, {
          vid: that.vid,
          mid: that.mid
        })
      },
      async ongrzlTap() {
        const that = this;
        let data = {};
        data.token = uni.getStorageSync("userinfo").token;
        data.uid = uni.getStorageSync("userinfo").id;
        uni.request({
          url: this.configs.apiUrl + '/api/user/index',
          data: data,
          success: res => {
            if (res.data.code == 1) {
              let ionfo = res.data.data
              ionfo.isLogin = true
              this.userinfo = ionfo
              this.jfdt = ionfo.config.jfdt ? ionfo.config.jfdt : ''
              uni.setStorage({
                key: 'userinfo',
                data: res.data.data
              })
              if (res.data.data.avatar) {
                var str = res.data.data.avatar;
                if (str.indexOf("data:image") != -1) {
                  this.avatar = '';
                } else {
                  if (str.indexOf("http") != -1) {
                    this.avatar = res.data.data.avatar;
                  } else {
                    this.avatar = this.configs.imgUrl + res.data.data.avatar;
                  }
                }
              } else {
                this.avatar = '';
              }
              uni.setStorage({ //快取配置資訊
                key: 'avatar',
                data: this.avatar
              })
            } else {
              if (res.data.code == 401) {
                uni.showToast({
                  title: 'need sign in',
                  duration: 2000,
                  success() {
                    const curRoute = that.$mp.page.route;
                    uni.reLaunch({
                      url: '/pages/login/login?redirect=' + curRoute,
                    })
                  }
                })
              }
              uni.showToast({
                title: res.data.msg,
                icon: "none"
              });
            }
          },
          fail: (data, code) => {
            console.log(data)
          }
        });
      }
    }
  }
</script>

<style lang="less">
  .pay-type-box {
    width: 100vw;
    height: auto;
    overflow: hidden;
    border-radius: 40rpx 40rpx 0px 0px;
    background-color: #fff;
  }

  .pay-type-title {
    position: relative;
    width: 100%;
    margin: 32rpx 0 36rpx;
    text-align: center;
    height: 56rpx;
    line-height: 56rpx;
    ;
  }

  .pay-type-title image.pay-type-close {
    position: absolute;
    right: 24rpx;
    top: 0;
    width: 56rpx;
    height: 56rpx;
  }

  .pay-type-info {
    margin-bottom: 8rpx;
  }

  .pay-type-list {
    padding: 0 32rpx;
    overflow-y: auto;
    margin-top: 48rpx;
  }

  .pay-type-item {
    width: 100%;
    margin-bottom: 32rpx;
    border: 2rpx solid #E9E9EB;
    border-radius: 200rpx;
    padding: 24rpx;
  }

  .pay-type-item.selected {
    border-color: #00CC5A;
  }

  .pay-type-item:last-child {
    margin-bottom: 0;
  }

  .pay-type-item image {
    width: 64rpx;
    height: 64rpx;
    margin-right: 24rpx;
  }

  .pay-type-item-title {
    flex-grow: 1;
  }

  .pay-type-item.disabled image,
  .pay-type-item.disabled .pay-type-item-title {
    opacity: 0.6;
  }

  .pay-type-footer {
    height: 240rpx;
    padding: 48rpx 32rpx 80rpx;
    margin-bottom: constant(safe-area-inset-bottom);
    margin-bottom: env(safe-area-inset-bottom);
  }

  .pay-type-footer.has-more {
    box-shadow: 0px -4px 12px 0px rgba(0, 0, 0, 0.16);
  }

  button.pay-type-btn {
    width: 100%;
    padding: 12rpx;
    border-radius: 200rpx;
    background-color: #00CC5A;
    color: #fff;
    font-size: 32rpx;
    font-weight: 600;
  }

  .recharge-header {
    height: 196rpx;
    width: 100%;
    position: relative;
  }

  .recharge-header image {
    width: 100%;
    height: 196rpx;
  }

  .recharge-header .main {
    position: absolute;
    width: 100%;
    height: 240rpx;
    left: 0;
    top: 0;
  }

  .topup-list {
    width: 686rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    gap: 24rpx;
  }

  .topup-list-item {
    position: relative;
    width: 48%;
    flex-direction: column;
    padding: 48rpx 0;
    border-radius: 24rpx;
    border: 2rpx solid #E9E9EB;
    background-color: #fff;
  }

  .topup-list-item.recommend {
    border: 2rpx solid #00CC5A;
    background: #FAFFFC;
  }
  
  .topup-list-item button {
    margin: 0 32rpx!important;
  }

  .topup-list-item.hot {
    background: #fff url(../../../static/img/payment/bg_more.png) right top no-repeat;
    background-size: 60%;
  }

  .topup-ratio {
    margin: 19rpx auto 26rpx;
    width: 140rpx;
    border: 2rpx solid #FE6B00;
    border-radius: 200rpx;
    color: #FE6B00;
    font-size: 28rpx;
    font-weight: 600;
    text-align: center;
    padding: 3rpx 10rpx;
  }

  .topup-list-item .recommend {
    position: absolute;
    left: -18rpx;
    top: -60rpx;
    width: 260rpx;
    height: 100rpx;
    background: url(../../../static/img/payment/tag_first.png) no-repeat center;
    background-size: contain;
  }

  .topup-list-item button {
    padding: 20rpx 40rpx;
  }

  .topup-list image {
    width: 40rpx;
    height: 40rpx;
  }

  .topup-list .money {
    color: #FEA300;
    text-align: center;
  }

  .topup-list button {
    padding: 20rpx 0;
    background-color: #00CC5A;
    border-radius: 200rpx;
    line-height: 40rpx;
    margin: 0;
  }

  .topup-list .radio {
    transform: scale(0.7)
  }

  .uni-radio .uni-radio-input {
    border: 1px solid var(--gray-500, #AEADB6);
    width: 16px;
    height: 16px;
  }

</style>